import random
import requests
from frame_work.type_file import (
    highQualitySource
)
from frame_work.util import (
    check_tid,
    change_user_account_status,
    assert_result_dict,
    get_sql_info,
    bind_tb
)
from frame_work.logger import Logger
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work.login import AppLogin
from frame_work import menu_list

logger = Logger(__name__).get_logger()


class AppSubmitOrder():
    # app提交订单号
    def __init__(self, tid, uname):
        self.uname = uname
        self.tid = tid
        self.sign = self.get_sign()
        self.info = self.get_try_info()
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    def get_sign(self):
        """
        app登录凭证
        :return:
        """
        app = AppLogin(self.uname)
        sign = app.appget_sign()
        return sign

    def get_try_info(self):
        """
        查询活动类型和店铺信息
        :return:
        """
        statement = """SELECT
                    t.type,
                    t.source,
                    t.shop_name,
                    j.jid,
                    j.buyer_uid AS uid
                FROM
                    sk_try t
                LEFT JOIN sk_join j ON t.tid = j.tid
                WHERE
                    t.tid = %s
                AND j.buyer_uname = %s
                """
        params = (self.tid, self.uname,)
        value = get_sql_info(statement, params, meta={
            "info": "查询提交订单所必须的活动参与信息"
        })
        return value

    def generate_random_nums(self, source, suffix):
        """
        根据活动来源生成对应随机数量订单号,淘宝后四位需要校验绑定的
        :param source: 活动来源
        :param suffix: 后四位
        :return:
        """
        if source in ('淘宝', '天猫', '淘宝特价版', '阿里巴巴', '抖音'):  # 商品来源为淘宝/天猫/抖音
            order_no = ''.join([str(random.randint(0, 9))
                               for i in range(0, 14)])
        elif source in ('京东', '京喜'):  # 商品来源为京东/京喜
            order_no = ''.join([str(random.randint(0, 9))
                               for i in range(0, 7)])
        elif source == '拼多多':  # 商品来源为拼多多
            order_no = ''.join([str(random.randint(0, 9)) for i in range(
                0, 6)]) + '-' + ''.join([str(random.randint(0, 9)) for i in range(0, 11)])
        else:  # 商品来源其它包括：微店、划算自营、其它
            order_no = ''.join([str(random.randint(0, 9))
                               for i in range(0, 2)])
        return order_no + str(suffix)

    def app_verify_shop(self, shop_name):
        """
        提交订单号前先验证店铺
        :param shop_name:
        :return:
        """
        yaml_data = self.yaml.get_data('app_verify_shop')
        yaml_data.get('data').update({
            'uid': self.info[0].get("uid"),
            'sign': self.sign,
            'shop_name': shop_name,
            'jid': self.info[0].get("jid")
        })
        response = requests.post(url=yaml_data.get('url'), data=yaml_data.get('data'),
                                 headers=yaml_data.get('header')).text
        if '"code":"OK"' in response:
            logger.debug("验证店铺成功...")
            return True
        else:
            logger.debug("验证店铺失败...")
            return False

    def app_submit_order(self, no):
        """
        app端活动填写订单号
        :param no:订单号
        :return:
        """
        yaml_data = self.yaml.get_data('app_submit_order')
        yaml_data.get('data').update({
            'uid': self.info[0].get("uid"),
            'sign': self.sign,
            'no': no,
            'jid': self.info[0].get("jid")
        })
        return requests.post(url=yaml_data.get('url'), data=yaml_data.get(
            'data'), headers=yaml_data.get('header')).text

    def app_modify_order(self, no):
        """
        app端活动修改订单号
        :param no:订单号
        :return:
        """
        yaml_data = self.yaml.get_data('app_modify_order')
        yaml_data.get('data').update({
            'uid': self.info[0].get("uid"),
            'sign': self.sign,
            'no': no,
            'jid': self.info[0].get("jid")
        })
        return requests.post(url=yaml_data.get('url'), data=yaml_data.get('data'),
                             headers=yaml_data.get('header')).text

    def app_submit_no(self, flag=1):
        """
        app端提交订单号
        :param flag:区别修改订单号还是提交订单号
        :return:
        """
        # 如果用户状态不对，改为正常
        account_status = change_user_account_status(self.uname)
        # 没绑淘宝就开始绑订
        tb_status = bind_tb(self.uname)
        if not(account_status and tb_status):
            return False
        logger.debug("精品试用提交订单号前需要验证店铺...")
        shop_name = self.info[0].get("shop_name")
        self.app_verify_shop(shop_name)
        source = highQualitySource(self.info[0].get('source')).name
        statement = """select valid_trade_suffix from sk_user_bind_taobao where uid = %s"""
        suffix = get_sql_info(statement, (self.info[0].get("uid"),), meta={
            "info": "查询绑定淘宝号的后四位数字"
        })
        order_no = self.generate_random_nums(
            source, suffix[0].get('valid_trade_suffix'))  # 根据来源生成订单号
        if flag != 1:
            logger.debug("开始修改订单号...")
            response_data = self.app_modify_order(order_no)
        else:
            logger.debug("开始提交订单号...")
            response_data = self.app_submit_order(order_no)
        logger.debug(response_data)
        assert_result_dict(
            response_data, self.uname + '%s订单号:%s' %
            ('提交' if flag == 1 else'修改', order_no))


def main():
    while True:
        # 显示功能菜单
        menu_list.quality_submit_order_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            buyer_name = input(u'请输入要提交单号的试客名称: ')
            if choise == '1':
                app_submit = AppSubmitOrder(tid, buyer_name)
                app_submit.app_submit_no(flag=1)
            elif choise == '2':
                app_submit = AppSubmitOrder(tid, buyer_name)
                app_submit.app_submit_no(flag=2)
            else:
                logger.info("没有对应的选项,请按选项输入...")
                break


if __name__ == "__main__":
    main()
    # get_dic_value(typev,8)
